import { defineStore } from 'pinia'
import { DatabaseService } from '@/services/database'

export const useDatabaseStore = defineStore('database', {
  state: () => ({
    // 数据库元数据缓存
    databases: new Map(), // connectionId -> databases[]
    tables: new Map(),    // connectionId:database -> tables[]
    columns: new Map(),   // connectionId:database:table -> columns[]
    indexes: new Map(),   // connectionId:database:table -> indexes[]
    
    // 查询历史
    queryHistory: [],
    
    // 当前查询结果
    currentResults: new Map(), // tabId -> results
    
    // 加载状态
    loading: {
      databases: false,
      tables: false,
      columns: false,
      indexes: false,
      query: false
    },
    
    // 错误信息
    errors: new Map(),
    
    // 支持的数据库类型
    supportedTypes: [],
    
    // 数据库类型信息
    typeInfo: {}
  }),
  
  getters: {
    // 获取指定连接的数据库列表
    getDatabases: (state) => (connectionId) => {
      return state.databases.get(connectionId) || []
    },
    
    // 获取指定数据库的表列表
    getTables: (state) => (connectionId, database) => {
      const key = `${connectionId}:${database}`
      return state.tables.get(key) || []
    },
    
    // 获取指定表的列信息
    getColumns: (state) => (connectionId, database, table) => {
      const key = `${connectionId}:${database}:${table}`
      return state.columns.get(key) || []
    },
    
    // 获取指定表的索引信息
    getIndexes: (state) => (connectionId, database, table) => {
      const key = `${connectionId}:${database}:${table}`
      return state.indexes.get(key) || []
    },
    
    // 获取查询结果
    getQueryResults: (state) => (tabId) => {
      return state.currentResults.get(tabId)
    },
    
    // 获取最近的查询历史
    getRecentQueries: (state) => (limit = 10) => {
      return state.queryHistory
        .slice()
        .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
        .slice(0, limit)
    },
    
    // 获取指定连接的查询历史
    getConnectionQueries: (state) => (connectionId, limit = 10) => {
      return state.queryHistory
        .filter(query => query.connectionId === connectionId)
        .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
        .slice(0, limit)
    },
    
    // 检查是否正在加载
    isLoading: (state) => (type) => {
      return state.loading[type] || false
    }
  },
  
  actions: {
    // 加载支持的数据库类型
    async loadSupportedTypes() {
      try {
        const types = await DatabaseService.getSupportedDatabaseTypes()
        this.supportedTypes = types || []
        
        const typeInfo = await DatabaseService.getDatabaseTypeInfo()
        this.typeInfo = typeInfo || {}
      } catch (error) {
        console.error('Failed to load supported types:', error)
      }
    },
    
    // 加载数据库列表
    async loadDatabases(connectionId, force = false) {
      if (!force && this.databases.has(connectionId)) {
        return this.databases.get(connectionId)
      }
      
      this.loading.databases = true
      this.errors.delete(`databases:${connectionId}`)
      
      try {
        const databases = await DatabaseService.listDatabases(connectionId)
        this.databases.set(connectionId, databases || [])
        return databases
      } catch (error) {
        this.errors.set(`databases:${connectionId}`, error.message)
        console.error('Failed to load databases:', error)
        throw error
      } finally {
        this.loading.databases = false
      }
    },
    
    // 加载表列表
    async loadTables(connectionId, database, force = false) {
      const key = `${connectionId}:${database}`
      
      if (!force && this.tables.has(key)) {
        return this.tables.get(key)
      }
      
      this.loading.tables = true
      this.errors.delete(`tables:${key}`)
      
      try {
        const tables = await DatabaseService.listTables(connectionId, database)
        this.tables.set(key, tables || [])
        return tables
      } catch (error) {
        this.errors.set(`tables:${key}`, error.message)
        console.error('Failed to load tables:', error)
        throw error
      } finally {
        this.loading.tables = false
      }
    },
    
    // 加载表列信息
    async loadColumns(connectionId, database, table, force = false) {
      const key = `${connectionId}:${database}:${table}`
      
      if (!force && this.columns.has(key)) {
        return this.columns.get(key)
      }
      
      this.loading.columns = true
      this.errors.delete(`columns:${key}`)
      
      try {
        const columns = await DatabaseService.getTableColumns(connectionId, database, table)
        this.columns.set(key, columns || [])
        return columns
      } catch (error) {
        this.errors.set(`columns:${key}`, error.message)
        console.error('Failed to load columns:', error)
        throw error
      } finally {
        this.loading.columns = false
      }
    },
    
    // 加载表索引信息
    async loadIndexes(connectionId, database, table, force = false) {
      const key = `${connectionId}:${database}:${table}`
      
      if (!force && this.indexes.has(key)) {
        return this.indexes.get(key)
      }
      
      this.loading.indexes = true
      this.errors.delete(`indexes:${key}`)
      
      try {
        const indexes = await DatabaseService.getTableIndexes(connectionId, database, table)
        this.indexes.set(key, indexes || [])
        return indexes
      } catch (error) {
        this.errors.set(`indexes:${key}`, error.message)
        console.error('Failed to load indexes:', error)
        throw error
      } finally {
        this.loading.indexes = false
      }
    },
    
    // 执行查询
    async executeQuery(connectionId, sql, tabId = null) {
      this.loading.query = true
      
      try {
        const result = await DatabaseService.executeQuery(connectionId, sql)
        
        // 转换查询结果格式 - 将后端格式转换为前端需要的格式
        const transformedResult = this.transformQueryResult(result)
        
        // 保存查询结果
        if (tabId) {
          this.currentResults.set(tabId, transformedResult)
        }
        
        // 添加到查询历史
        this.addToQueryHistory({
          connectionId,
          sql,
          result: transformedResult,
          timestamp: new Date(),
          success: !transformedResult.error
        })
        
        return transformedResult
      } catch (error) {
        // 添加失败的查询到历史
        this.addToQueryHistory({
          connectionId,
          sql,
          error: error.message,
          timestamp: new Date(),
          success: false
        })
        
        throw error
      } finally {
        this.loading.query = false
      }
    },
    
    // 转换查询结果格式 - 将后端的格式转换为前端组件需要的格式
    transformQueryResult(result) {
      if (!result) return null
      
      console.log('Store - 原始后端结果:', result)
      
      // 如果有错误，直接返回
      if (result.error) {
        return {
          error: result.error,
          executeTime: result.execute_time || 0
        }
      }
      
      // 提取列名数组
      const columnNames = result.columns || []
      
      console.log('Store - 列名:', columnNames)
      console.log('Store - 行数据示例:', result.rows?.[0])
      
      // 将后端格式转换为前端需要的格式
      const transformed = {
        // 转换列信息 - 后端返回的是字符串数组，需要转换为对象数组
        columns: columnNames.map(name => ({
          name: name,
          type: 'string', // 默认类型，后续可以根据实际数据推断
          width: 150
        })),
        // 数据已经是正确的格式（对象数组）
        data: result.rows || [],
        rowCount: result.row_count || (result.rows ? result.rows.length : 0),
        affectedRows: result.affected_rows || 0,
        executeTime: result.execute_time || 0,
        error: result.error || null
      }
      
      console.log('Store - 转换后结果:', transformed)
      
      return transformed
    },
    
    // 执行非查询语句
    async executeNonQuery(connectionId, sql) {
      this.loading.query = true
      
      try {
        const affectedRows = await DatabaseService.executeNonQuery(connectionId, sql)
        
        // 添加到查询历史
        this.addToQueryHistory({
          connectionId,
          sql,
          affectedRows,
          timestamp: new Date(),
          success: true
        })
        
        return affectedRows
      } catch (error) {
        // 添加失败的查询到历史
        this.addToQueryHistory({
          connectionId,
          sql,
          error: error.message,
          timestamp: new Date(),
          success: false
        })
        
        throw error
      } finally {
        this.loading.query = false
      }
    },
    
    // 添加到查询历史
    addToQueryHistory(queryRecord) {
      // 限制历史记录数量
      const maxHistory = 1000
      
      this.queryHistory.unshift({
        id: Date.now(),
        ...queryRecord
      })
      
      if (this.queryHistory.length > maxHistory) {
        this.queryHistory = this.queryHistory.slice(0, maxHistory)
      }
      
      // 保存到本地存储
      this.saveQueryHistory()
    },
    
    // 清除查询历史
    clearQueryHistory() {
      this.queryHistory = []
      localStorage.removeItem('database-query-history')
    },
    
    // 删除指定查询历史
    removeQueryHistory(queryId) {
      const index = this.queryHistory.findIndex(q => q.id === queryId)
      if (index >= 0) {
        this.queryHistory.splice(index, 1)
        this.saveQueryHistory()
      }
    },
    
    // 保存查询历史到本地存储
    saveQueryHistory() {
      try {
        const historyToSave = this.queryHistory.slice(0, 100) // 只保存最近100条
        localStorage.setItem('database-query-history', JSON.stringify(historyToSave))
      } catch (error) {
        console.warn('Failed to save query history:', error)
      }
    },
    
    // 从本地存储恢复查询历史
    restoreQueryHistory() {
      try {
        const saved = localStorage.getItem('database-query-history')
        if (saved) {
          this.queryHistory = JSON.parse(saved)
        }
      } catch (error) {
        console.warn('Failed to restore query history:', error)
        this.queryHistory = []
      }
    },
    
    // 清除指定连接的缓存
    clearConnectionCache(connectionId) {
      // 清除数据库列表
      this.databases.delete(connectionId)
      
      // 清除表列表
      for (const key of this.tables.keys()) {
        if (key.startsWith(`${connectionId}:`)) {
          this.tables.delete(key)
        }
      }
      
      // 清除列信息
      for (const key of this.columns.keys()) {
        if (key.startsWith(`${connectionId}:`)) {
          this.columns.delete(key)
        }
      }
      
      // 清除索引信息
      for (const key of this.indexes.keys()) {
        if (key.startsWith(`${connectionId}:`)) {
          this.indexes.delete(key)
        }
      }
      
      // 清除错误信息
      for (const key of this.errors.keys()) {
        if (key.includes(connectionId)) {
          this.errors.delete(key)
        }
      }
    },
    
    // 刷新指定连接的所有缓存
    async refreshConnectionCache(connectionId) {
      this.clearConnectionCache(connectionId)
      
      try {
        // 重新加载数据库列表
        await this.loadDatabases(connectionId, true)
      } catch (error) {
        console.error('Failed to refresh connection cache:', error)
      }
    },
    
    // 设置查询结果（用于批量执行等特殊场景）
    setQueryResults(tabId, result) {
      if (tabId && result) {
        this.currentResults.set(tabId, result)
      }
    },
    
    // 清除查询结果
    clearQueryResults(tabId) {
      if (tabId) {
        this.currentResults.delete(tabId)
      } else {
        this.currentResults.clear()
      }
    },
    
    // 获取错误信息
    getError(key) {
      return this.errors.get(key)
    },
    
    // 清除错误信息
    clearError(key) {
      if (key) {
        this.errors.delete(key)
      } else {
        this.errors.clear()
      }
    },
    
    // 重置store
    reset() {
      this.databases.clear()
      this.tables.clear()
      this.columns.clear()
      this.indexes.clear()
      this.currentResults.clear()
      this.errors.clear()
      this.queryHistory = []
      this.loading = {
        databases: false,
        tables: false,
        columns: false,
        indexes: false,
        query: false
      }
    }
  }
}) 